/*
 * @Author: xiaosihan 
 * @Date: 2023-12-15 14:21:41 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-10-31 02:19:17
 */

import largeScreenApi from '@api/largeScreenApi';
import Title2 from '@components/Title2/Title2';
import ReactEcharts from 'echarts-for-react';
import { uniq } from 'lodash';
import { autorun, toJS } from "mobx";
import { ReactNode, useEffect, useState } from "react";
import centerTopStore from '../CenterTop/centerTopStore';
import doubtfulSituationStore from "../doubtfulSituationStore";
import { getOptions } from "./instants";
import styles from "./personAndInstitutioRelation.module.less";

interface Iprops {
    children?: ReactNode
}

// 风险机构被检出的风险疑点情况
export default function PersonAndInstitutioRelation(props: Iprops) {

    const [top, setTop] = useState("10%");
    const [bottom, setBottom] = useState("6%");

    const [nodes, setNodes] = useState<Array<{ name: string } & { [key: string]: any }>>([]);
    const [links, setLinks] = useState<Array<{ source: string; target: string, value: number }>>([]);

    const colorList = ['#287CE8', '#E79145', '#41E4DE', '#FFC24D', '#32B8F0'];

    function chunkArrayToTwoWithEqualLength(arr: Array<string>) {
        let chunk1 = [];
        let chunk2 = [];
        let totalLength = arr.reduce((acc, curr) => acc + curr.length, 0);
        let currentLength1 = 0;
        let currentLength2 = 0;

        for (let i = 0; i < arr.length; i++) {
            // 尝试将当前字符串放入第一个数组
            if (currentLength1 <= currentLength2 &&
                currentLength1 + arr[i].length <= totalLength / 2) {
                chunk1.push(arr[i]);
                currentLength1 += arr[i].length;
            } else {
                // 如果第一个数组长度超过或等于第二个数组，或者第一个数组加上当前字符串长度超过总长度的一半，则放入第二个数组
                chunk2.push(arr[i]);
                currentLength2 += arr[i].length;
            }
        }

        return [chunk1, chunk2];
    }

    useEffect(() => autorun(async () => {
        const { active } = centerTopStore;

        // let riskData = toJS(doubtfulSituationStore.institutional_risk_index);
        // debugger;
        let res = await largeScreenApi.institutional_risk_index() as any;
        let riskData = res.list;
        // debugger;
        let modelList = toJS(doubtfulSituationStore.regulatory_model_List);

        // 根据模型来筛选
        if (modelList[active]) {
            riskData = riskData.filter((d: any) => d.checkout_model.includes(modelList[active].model_name));
        }

        console.log("上面的数据");
        console.log(riskData);

        const data = toJS(doubtfulSituationStore.person_and_institutio_relation) as Array<{ nurscare_org_no: string, nurscare_org_name: string, risk_model: string, risk_cnt: number, model_name: string }>;

        console.log("下面的全部数据");
        console.log(data);

        // 风险模型数组
        let risk_models: Array<string> = data
            .filter(d => riskData.some((rd: any) => rd.nurscare_org_no === d.nurscare_org_no))
            .map(obj => obj.model_name).join(",").split(",");

        risk_models = uniq(risk_models);
        let risk_model_array = chunkArrayToTwoWithEqualLength(risk_models);
        // 机构组
        let nurscare: Array<string> = riskData.map((obj: any) => obj.nurscare_org_name);

        //节点
        let nodes = [
            ...risk_models.map(m => ({
                name: m,
                itemStyle: {
                    color: "#0D4294",
                }
            })),
            ...nurscare.map((n, i) => ({
                name: n,
                itemStyle: {
                    color: colorList[i],
                }
            }))
        ];
        setNodes(nodes);
        // 链接
        let links: Array<{ source: string; target: string, value: number }> = [];
        data.map(obj => {
            let risk_models = obj.model_name.split(",");
            risk_models.map(risk => {
                if (risk_model_array[0].includes(risk)) {
                    links.push({
                        source: risk,
                        target: obj.nurscare_org_name,
                        value: obj.risk_cnt,
                    });
                } else {
                    links.push({
                        source: obj.nurscare_org_name,
                        target: risk,
                        value: obj.risk_cnt,
                    });
                }
            });
        });
        setLinks(links);
    }), []);

    // const mouseover = (item: any) => {
    //     if (item.value === 2) {
    //         const data = toJS(doubtfulSituationStore.person_and_institutio_relation) as Array<{ source: string, target: string }>;
    //         const result = data.filter(obj => {
    //             return obj.source === item.name
    //         });
    //         setData(result.slice(0, 6));
    //         setTop("1%");
    //         setBottom("1%");
    //     }
    // }

    // const mouseout = (item: any) => {

    //     const data = toJS(doubtfulSituationStore.person_and_institutio_relation) as Array<{ source: string, target: string }>;

    //     // 同一家医院只保留2个
    //     const countMap: { [key: string]: number } = {}; // 用于记录每个source出现的次数
    //     let uniqueSources = 0; // 记录不同的source的数量

    //     const result = data.filter(obj => {
    //         if (countMap[obj.source]) {
    //             countMap[obj.source]++;
    //         } else {
    //             countMap[obj.source] = 1;
    //             uniqueSources++;
    //         }
    //         return countMap[obj.source] <= 2 && uniqueSources <= 6;
    //     });

    //     setTop("6%");
    //     setBottom("6%");
    // }




    return (
        <div className={styles.personAndInstitutioRelation}>
            <Title2 left={0} top={-50} >风险机构被检出的风险疑点情况</Title2>
            <ReactEcharts
                className={styles.chart}
                option={getOptions(nodes, links, top, bottom)}
            />
        </div>
    );

}